package com.android.car_bluetooth_audio.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;


import com.android.car_bluetooth_audio.R;
import com.android.car_bluetooth_audio.utils.DensityUtils;

import java.util.Timer;
import java.util.TimerTask;

public class ProgressBarView extends View {

    /**
     * 进度条所占用的角度
     */
    private static final int ARC_FULL_DEGREE = 270;
    /**
     * 弧线的宽度
     */
    private int STROKE_WIDTH;
    /**
     * 组件的宽，高
     */
    private int width, height,sWidth,sHeight;

    /**
     * 进度条最大值和当前进度值
     */
    private float max, progress;

    /**
     * 是否允许拖动进度条
     */
    private boolean draggingEnabled = true;
    /**
     * 绘制弧线的矩形区域
     */
    private RectF circleRectF;  //,zhizhenRectF
    /**
     * 绘制弧线的画笔
     */
    private Paint progressPaint;
    /**
     * 绘制文字的画笔
     */
    private Paint textPaint;
    /**
     * 绘制当前进度值的画笔
     */
    private Paint thumbPaint;
    private int buttonRadius;
    /**
     * 圆弧的半径
     */
    private int circleRadius;
    /**
     * 圆弧圆心位置
     */
    private int centerX, centerY;
    private int upBtCenterX,upBtCenterY,downBtCenterx,downBtCenterY;//控制按钮的坐标
    private Bitmap zhizhen;
    private Matrix matrix;//矩阵--控制指针图片的动画
    /**
     * 指针圆心
     */
    private float circleRectFCenterWidth;
    private float circleRectFCenterHeight;
    private float newProgress;
    private OnChangeCallbackListener onChangeCallbackListener;
    private Timer mTestTimer;
    private boolean isSend;
    public ProgressBarView(Context context) {
//        super(context);
        this(context,null);
    }


    public ProgressBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }


    public ProgressBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }
    private void init(Context context, AttributeSet attrs) {
//    	position = new float[colors.length];
        zhizhen = BitmapFactory.decodeResource(getResources(), R.mipmap.zhizhen1);
        matrix = new Matrix();
        Log.e("init", "测试1");
        progressPaint = new Paint();
        progressPaint.setAntiAlias(true);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProgressBarView);
        final int N = typedArray.getIndexCount();
        for (int i = 0; i < N; i++) {
            initCustomAttr(typedArray.getIndex(i), typedArray);
        }
        typedArray.recycle();

        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setAntiAlias(true);


        thumbPaint = new Paint();
        thumbPaint.setAntiAlias(true);


        //使用自定义字体
//        textPaint.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fangz.ttf"));
    }

    private void initCustomAttr(int attr, TypedArray typedArray) {
        if (attr == R.styleable.ProgressBarView_max) {
            max = typedArray.getFloat(attr,max);
        } else if (attr == R.styleable.ProgressBarView_progress) {
            progress = typedArray.getFloat(attr, progress);
        }
    }

    public float getProgress(){
        return progress;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        Log.e("onMeasure", "获取长宽");
        if (width == 0 || height == 0) {
            sWidth = MeasureSpec.getSize(widthMeasureSpec);
            sHeight = MeasureSpec.getSize(heightMeasureSpec);
            width= (int) (zhizhen.getWidth()/1.5);
            height= (int) (zhizhen.getHeight()/1.5);



            System.out.println("width="+ width + " ; height="+ height);

            //计算圆弧半径和圆心点
            circleRadius = Math.min(width, height)*2/3 ;
            circleRadius -= STROKE_WIDTH;

            STROKE_WIDTH = circleRadius / 12*2;  //圆弧描边的宽度


            centerX = sWidth/ 2;
            centerY = centerX;
            // ratio = height/width;
            //圆弧所在矩形区域
            circleRectF = new RectF();
            circleRectF.left = centerX - circleRadius;
            circleRectF.top = centerY - circleRadius;
            circleRectF.right = centerX + circleRadius;
            circleRectF.bottom = centerY + circleRadius;

            //指针所在区域
//            zhizhenRectF = new RectF();
//            zhizhenRectF.left = centerX - circleRadius/1.6f;
//            zhizhenRectF.top = centerY - circleRadius/1.6f;
//            zhizhenRectF.right = centerX + circleRadius/1.6f;
//            zhizhenRectF.bottom = centerY + circleRadius/1.6f;

            circleRectFCenterWidth=(circleRectF.right+circleRectF.left)/2;
            circleRectFCenterHeight=(circleRectF.bottom+circleRectF.top)/2;

//           System.out.println("具体值："+zhizhenRectF.left + " "+ zhizhenRectF.right+" "+zhizhenRectF.top+" "+zhizhenRectF.bottom);
            Log.e("onMeasure", "获取长宽完成");
        }

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Log.e("ondraw", "测试2");

        float start = 90 + ((360 - ARC_FULL_DEGREE) >> 1); //进度条起始点
        float sweep1 = ARC_FULL_DEGREE * (progress / max); //进度划过的角度
        float sweep2 = ARC_FULL_DEGREE - sweep1; //剩余的角度
        float progressRadians = (float) (((360.0f - ARC_FULL_DEGREE) / 2 + sweep1) / 180 * Math.PI);
        float thumbX = centerX - (circleRadius-STROKE_WIDTH) * (float) Math.sin(progressRadians);
        float thumbY = centerY + (circleRadius-STROKE_WIDTH) * (float) Math.cos(progressRadians);

        //绘制起始位置小圆形
        progressPaint.setColor(Color.WHITE);
        progressPaint.setStrokeWidth(0);
        progressPaint.setStyle(Paint.Style.FILL);
        float radians = (float) (((360.0f - ARC_FULL_DEGREE) / 2) / 180 * Math.PI);
        float startX = centerX - circleRadius * (float) Math.sin(radians);
        float startY = centerY + circleRadius * (float) Math.cos(radians);
        System.out.println("startX=" + startX + ";startY="+ startY);
        canvas.drawCircle(startX, startY, STROKE_WIDTH / 2, progressPaint);

        //绘制-Min文字
        buttonRadius = circleRadius/8;
        downBtCenterx=(int) (startX+buttonRadius);
        downBtCenterY=(int) (startY+4*buttonRadius);
//        progressPaint.setColor(Color.parseColor("#8800FFFF"));
//        canvas.drawCircle(startX+buttonRadius, startY+4*buttonRadius, buttonRadius, progressPaint);
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(DensityUtils.sp2px(getContext(), 18));
        float len = textPaint.measureText("- MIN");
        canvas.drawText("- MIN", startX-len, startY+4*buttonRadius, textPaint);
        //绘制进度条
        progressPaint.setStrokeWidth(STROKE_WIDTH);
        progressPaint.setStyle(Paint.Style.STROKE);//设置空心
        progressPaint.setColor(Color.parseColor("#ab6053"));
//        LinearGradient linearGradient = new LinearGradient(startX, startY, thumbX, thumbY, colors, position, TileMode.CLAMP);
//        progressPaint.setShader(linearGradient);
        Log.e("start", String.valueOf(start));
        Log.e("sweep1", String.valueOf(sweep1));
        canvas.drawArc(circleRectF, start, sweep1, false, progressPaint);
        //绘制进度条背景
//        linearGradient=null;
        progressPaint.setShader(null);
        progressPaint.setColor(Color.parseColor("#fefeff"));
        canvas.drawArc(circleRectF, start + sweep1, sweep2, false, progressPaint);
        Log.e("onDraw", "测试-画进度条");

        //绘制结束位置小圆形
        progressPaint.setStrokeWidth(0);
        progressPaint.setStyle(Paint.Style.FILL);
        float endX = centerX + circleRadius * (float) Math.sin(radians);
        float endY = centerY + circleRadius * (float) Math.cos(radians);
        canvas.drawCircle(endX, endY, STROKE_WIDTH / 2, progressPaint);
        Log.e("onDraw", "测试-画按钮");

        // 绘制+ Min文字
        upBtCenterX=(int) (endX-buttonRadius);
        upBtCenterY=(int) (endY+4*buttonRadius);
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(DensityUtils.sp2px(getContext(), 18));
        float len1 = textPaint.measureText("MAX +");
        canvas.drawText("MAX +", endX, endY+4*buttonRadius, textPaint);

        //画出实心圆
        progressPaint.setColor(Color.parseColor("#9ca6b0"));
        progressPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(centerX, centerY, circleRadius, progressPaint);

        //绘制进度条上的按钮
//        thumbPaint.setColor(Color.parseColor("#33d64444"));
//        canvas.drawCircle(thumbX, thumbY, STROKE_WIDTH * 2.0f, thumbPaint);
//        thumbPaint.setColor(Color.parseColor("#99d64444"));
//        canvas.drawCircle(thumbX, thumbY, STROKE_WIDTH * 1.4f, thumbPaint);
        thumbPaint.setColor(Color.WHITE);
        canvas.drawCircle(thumbX, thumbY, STROKE_WIDTH * 0.8f, thumbPaint);
        Log.e("onDraw", "测试-完成");
        System.out.println("进度值progress="+progress);
    }

    private boolean isDragging = false;


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!draggingEnabled) {
            return super.onTouchEvent(event);
        }
        Log.e("onTouchEvent", "测试3");

        //处理拖动事件
        float currentX = event.getX();
        float currentY = event.getY();
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mTestTimer = new Timer();
                //判断是否在进度条thumb位置
                if (checkOnArc(currentX, currentY)) {
                    newProgress = calDegreeByPosition(currentX, currentY) / ARC_FULL_DEGREE * max;
                    setProgressSync(newProgress);
                    isDragging = true;
                } else if(checkOnButtonUp(currentX, currentY)){
                    // TODO Auto-generated method stub
                    setProgress(progress+10);
                    isDragging = false;
                }else if(checkOnButtonDwon(currentX, currentY)){
                    setProgress(progress-10);
                    isDragging = false;
                }

                break;


            case MotionEvent.ACTION_MOVE:
                if (isDragging) {
                    //判断拖动时是否移出去了
                    if (checkOnArc(currentX, currentY)) {
                        setProgressSync(calDegreeByPosition(currentX, currentY) / ARC_FULL_DEGREE * max);
                        Log.e("isSEnd", String.valueOf(isSend));
                        if (!isSend){
                            isSend=true;
                            if (mTestTimer!=null){
                                mTestTimer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        Log.e("进入这哦","好的");
                                        if (onChangeCallbackListener != null) {
                                            onChangeCallbackListener.onChangeListener(progress,max);
                                        }
                                    }
                                },0,200);
                            }

                        }

                    } else {
                        isDragging = false;
                    }
                }

                break;


            case MotionEvent.ACTION_UP:
                isDragging = false;
                if(mTestTimer!=null)
                {
                    mTestTimer.cancel();
                    mTestTimer.purge();
                }
                isSend=false;
                if (onChangeCallbackListener != null) {
//                    float v = checkProgress(calDegreeByPosition(currentX, currentY));
                    Log.e("prog是多少", String.valueOf(progress));
//                    float newProgress1 = v / ARC_FULL_DEGREE * max;
//                    Log.e("转过的角度", String.valueOf(v));

                    onChangeCallbackListener.onChangeListener(progress,max);
                }

                break;
        }
        return true;

    }

    public void setChangeCallbackListener(OnChangeCallbackListener listener) {
        this.onChangeCallbackListener = listener;
    }

    private float calDistance(float x1, float y1, float x2, float y2) {
        return (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    private boolean checkOnButtonUp(float currentX,float currentY){
        float distance = calDistance(currentX, currentY, upBtCenterX, upBtCenterY);
        return distance < 1.5*buttonRadius;
    }

    private boolean checkOnButtonDwon(float currentX,float currentY){
        float distance = calDistance(currentX, currentY, downBtCenterx, downBtCenterY);
        return distance < 1.5*buttonRadius;
    }
    /**
     * 判断该点是否在弧线上（附近）
     */
    private boolean checkOnArc(float currentX, float currentY) {
        float distance = calDistance(currentX, currentY, centerX, centerY);
        float degree = calDegreeByPosition(currentX, currentY);
        return distance > circleRadius - STROKE_WIDTH * 5 && distance < circleRadius + STROKE_WIDTH * 5
                && (degree >= -8 && degree <= ARC_FULL_DEGREE + 8);
    }

    /**
     * 根据当前位置，计算出进度条已经转过的角度。
     */
    private float calDegreeByPosition(float currentX, float currentY) {
        float a1 = (float) (Math.atan(1.0f * (centerX - currentX) / (currentY - centerY)) / Math.PI * 180);
        if (currentY < centerY) {
            a1 += 180;
        } else if (currentY > centerY && currentX > centerX) {
            a1 += 360;
        }


        return a1 - (360 - ARC_FULL_DEGREE) / 2;
    }


    public void setMax(int max) {
        this.max = max;
        invalidate();
    }

    public void setProgress(float progress) {
        final float validProgress = checkProgress(progress);
        //动画切换进度值
        new Thread(new Runnable() {
            @Override
            public void run() {
                float oldProgress = ProgressBarView.this.progress;
                for (int i = 1; i <= 100; i++) {
                    ProgressBarView.this.progress = oldProgress + (validProgress - oldProgress) * (1.0f * i / 100);
                    postInvalidate();
                    SystemClock.sleep(3);
                }
            }
        }).start();
    }

    public void setProgressSync(float progress) {
        this.progress = checkProgress(progress);
        invalidate();
    }



    //保证progress的值位于[0,max]
    private float checkProgress(float progress) {
        if (progress < 0) {
            return 0;
        }


        return progress > max ? max : progress;
    }


    public void setDraggingEnabled(boolean draggingEnabled) {
        this.draggingEnabled = draggingEnabled;
    }

    public interface OnChangeCallbackListener {
        void onChangeListener(float value,float max);
    }
}
